package edu.gdut.thesissys.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;

import edu.gdut.thesissys.dao.DaoFactory;
import edu.gdut.thesissys.vo.Major;
import edu.gdut.thesissys.vo.Teacher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FindMajorsService {

	private static final Logger log = LoggerFactory
			.getLogger(FindMajorsService.class);
	@Resource(name = "daoFactory")
	private DaoFactory daoFactory;

	public JSONArray findMajorsJson() {
		JSONArray majorsArray = new JSONArray();
		log.debug("find all majorsJson");
		try {
			Integer teacherId = (Integer) ActionContext.getContext()
					.getSession().get("ID");
			Set<Major> majorSet = findMajors(teacherId);// 获得majors
			// 提取major信息
			for (Major major : majorSet) {
				JSONObject majorJson = new JSONObject();
				majorJson.put("id", major.getMajorId());
				majorJson.put("name", major.getName());
				majorJson.put("department", major.getDepartment().getName());
				majorsArray.add(majorJson);
			}
		} catch (Exception e) {
			log.error("find all majorsJson failed", e);
			return new JSONArray();
		}
		log.debug("find all majorsJson successfule and return data: "
				+ majorsArray.toString());
		return majorsArray;
	}

	public List<Major> findAllMajors() {
		List<Major> majorList = new ArrayList<Major>(0);
		log.debug("find all majors");
		try {
			majorList = daoFactory.getBaseDAO(Major.class).findAll();
		} catch (Exception e) {
			log.error("find all majors failed", e);
			return new ArrayList<Major>(0);
		}
		log.debug("find all majors successful " + majorList);
		return majorList;
	}

	public Set<Major> findMajors(int teacherId) {
		Set<Major> majorSet = new HashSet<Major>(0);
		log.debug("find majors by teacherId " + teacherId);
		try {
			Teacher teacher = daoFactory.getBaseDAO(Teacher.class).findById(
					teacherId);
			if (teacher != null) {
				String power = teacher.getPowerRight();
				// 系（副）主任权限或教研（副）主任
				if (power.equals("2") || power.equals("3")) {
					majorSet = teacher.getDepartment().getMajors();// 只能获得所负责系的专业
					// （副）院长权限
				} else if (power.equals("4")) {
					List<Major> majorList = findAllMajors();// 获得学院全部专业
					for (Major major : majorList) {
						majorSet.add(major);
					}
				}
			}
		} catch (Exception e) {
			log.error("find majors by teacherId " + teacherId + " failed", e);
			return new HashSet<Major>(0);
		}
		log.debug("find majors successful");
		return majorSet;
	}

}
